package com.qen.socket.aio

import cn.hutool.core.date.DateUtil
import cn.hutool.core.io.BufferUtil
import cn.hutool.core.lang.Console
import cn.hutool.core.util.StrUtil
import cn.hutool.log.StaticLog
import cn.hutool.socket.SocketConfig
import cn.hutool.socket.aio.AioServer
import cn.hutool.socket.aio.AioSession
import cn.hutool.socket.aio.SimpleIoAction
import java.net.InetSocketAddress
import java.nio.ByteBuffer

fun main() {
    val address = InetSocketAddress("0.0.0.0",8899)
    val config = SocketConfig()
    config.readTimeout = 20000
    config.writeTimeout = 20000
    val server = AioServer(address,config)

    server.setIoAction(object : SimpleIoAction() {
        override fun accept(session: AioSession?) {
            Console.log(session)
            StaticLog.debug("[客户端]：${session?.remoteAddress}连接")
            session?.write(BufferUtil.createUtf8("==== Welcome to Hutool socket server. ===="))
//            super.accept(session)
        }

        override fun doAction(session: AioSession?, data: ByteBuffer?) {
            Console.log(data)
            if (false == data?.hasRemaining()) {
                val response = """
                        HTTP/1.1 200 OK
                        Date: ${DateUtil.formatHttpDate(DateUtil.date())}
                        Content-Type: text/html; charset=UTF-8
                        Hello Hutool socket
                        """
                session?.writeAndClose(BufferUtil.createUtf8(response))
            } else {
                session?.read()
            }

        }
    }).start(true)
}